package com.lsh.oms.worker.service.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dangdang.ddframe.job.api.JobExecutionMultipleShardingContext;
import com.dangdang.ddframe.job.plugin.job.type.dataflow.AbstractIndividualThroughputDataFlowElasticJob;
import com.lsh.base.trace.id.filter.TraceIdSetter;
import com.lsh.oms.core.enums.LogisticsModel;
import com.lsh.oms.core.enums.OrderStatus;
import com.lsh.oms.core.model.order.OrderHead;
import com.lsh.oms.core.proxy.model.Position;
import com.lsh.oms.core.proxy.model.user.UserContent;
import com.lsh.oms.core.proxy.service.FenceServiceProxy;
import com.lsh.oms.core.proxy.service.MisProxy;
import com.lsh.oms.core.proxy.service.UserServiceProxy;
import com.lsh.oms.core.service.order.OrderQueryService;
import com.lsh.oms.core.service.order.OrderUpdateService;
import com.lsh.oms.worker.service.service.OrderCommit2OfcService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单提交OFC
 *
 * @author huangdong
 * @date 17/1/8
 */
@Component
public class OrderFillOpsJob extends AbstractIndividualThroughputDataFlowElasticJob<OrderHead> implements InitializingBean {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private OrderQueryService orderQueryService;
    @Autowired
    private OrderUpdateService orderUpdateService;
    @Autowired
    private UserServiceProxy userServiceProxy;
    @Autowired
    private MisProxy misProxy;
    @Autowired
    private FenceServiceProxy fenceServiceProxy;
    @Autowired
    private OrderCommit2OfcService orderCommit2OfcService;

    @Value("${shopUrl}")
    private String shopUrl;

    @Override
    public void afterPropertiesSet() throws Exception {
    }


    @Override
    public List<OrderHead> fetchData(JobExecutionMultipleShardingContext context) {
        TraceIdSetter.set();
        logger.info("订单提交fill fetchData start...");
        OrderHead filter = new OrderHead();
        filter.setOrderStatus(OrderStatus.ORDER_COMMITING_OFC.getIndex());
        List<OrderHead> list = this.orderQueryService.findList(filter, false, false);
        logger.info("订单提交fill fetchData size=" + list.size());

        return list;
    }

    @Override
    public boolean processData(JobExecutionMultipleShardingContext context, OrderHead model) {

        Long orderCode = model.getOrderCode();
        try {

            boolean ret = this.fillOps(model, model.getOrderCode() + "");
            return true;
        } catch (Throwable t) {
            logger.error("订单提交OFC processData(" + orderCode + ") end... 提交错误. error message:" + t.getMessage());
            throw t;
        }

    }

    /**
     * 提交OFC
     *
     * @param head
     * @return
     */
    private boolean fillOps(OrderHead head, String logSign) {

        Long orderCode = head.getOrderCode();
        Long addressId = head.getAddressCode();
        JSONObject extJson = JSON.parseObject(head.getExt());
        String orderDc = extJson.getString("orderDc");
        Integer logisticsModeDb = extJson.getInteger("logisticsMode");

        String supplierGroup = userServiceProxy.getSupplierGroup(head.getAddressCode().toString(),head.getVenderId());
        logger.info(orderCode + " supplierGroup  fill is "  + supplierGroup);
        if(StringUtils.isEmpty(supplierGroup)){
            logger.info("{} supplierGroupid [{}],请求商城用户信息异常", logSign, supplierGroup);
            return false;
        }

        if (null != logisticsModeDb) {
            return true;
        }

//        UserContent userContent = this.userServiceProxy.getUserInfo(String.valueOf(addressId), head.getVenderId());
//        if (null == userContent) {
//            logger.info("{} 地址id [{}],请求商城用户信息异常", logSign, addressId);
//            return false;
//        }
//
//        logger.info("saas userContent is " + JSON.toJSONString(userContent));

//                this.orderCommit2OfcService.parsePosition(userContent.getAddressInfo());
//        if (position == null) {
//            logger.info("订单提交fill false 地址id [{}],解析用户经纬度坐标错误", addressId);
//            return false;
//        }
//        this.fenceServiceProxy.getFenceId(position, userContent.getAddressInfo().getCounty());
//        JSON.parseObject(head.getAddressInfo());

        // 查询围栏服务，获取前置仓围栏信息
        Position position = new Position();
        Map<String, Object> fenceInfo = new HashMap<>();
        JSONObject addressInfo = new JSONObject();
        UserContent userContent = new UserContent();
        // 请求策略服务，决定订单物流模式
        Integer logisticsMode = this.orderCommit2OfcService.obtainOrderLogisticsMode(logSign, head, addressInfo, userContent, position, fenceInfo,supplierGroup);
        if (logisticsMode == null) {
            logger.info("addressInfo {} 策略服务返回策略模式为空", addressInfo);
            return false;
        }

        extJson.put("logisticsMode", logisticsMode);

        if(logisticsMode.equals(LogisticsModel.CLOUD_DC_2_DC.getType())){
            extJson.put("parentHaveCloudChildren", "1");
        }

        OrderHead update = new OrderHead();
        update.setSupplierGroupId(supplierGroup);
        update.setExt(extJson.toJSONString());
        OrderHead filter = new OrderHead();
        filter.setOrderCode(orderCode);
        if (orderUpdateService.updateOrderHead(update, filter) >= 1) {

            return true;
        }

        return false;
    }


}
